package com.sparkseries.common.security.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sparkseries.common.security.domain.SecurityUser;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class JwtUtil {
//    @Value("${my.secret}")
    private final String secret = "spark";  // 密钥

    @Resource
    private ObjectMapper objectMapper;

    public String createJwt(String userInfo) throws UnsupportedEncodingException {
        // 设置JWT头部信息
        Map<String, Object> headerClaims = new HashMap<>();
        headerClaims.put("alg", "HS256");
        headerClaims.put("typ", "JWT");

        // 设置签发时间
        Date currentTime = new Date();

        // 设置过期时间为两小时
        Date expireTime = new Date(currentTime.getTime() + 1000*60*60*2);

        return JWT.create().withHeader(headerClaims)
                .withIssuer("Spark")  // 设置签发人
                .withIssuedAt(currentTime)  // 设置签发时间
                .withExpiresAt(expireTime)  // 设置过期时间
                .withClaim("userInfo", userInfo)  // 自定义声明：用户信息
                .sign(Algorithm.HMAC256(secret));  // 使用HS256进行签名，使用secret作为密钥
    }

    // 验证Token是否正确
    public boolean verifyToken(String jwt) {
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();

            jwtVerifier.verify(jwt);

            log.info("Token验证成功！");

            return true;
        } catch (Exception e) {
            log.error("Token验证失败！");
            return false;
        }
    }

    // 根据Token获取用户信息
    public SecurityUser getUserInfo(String jwt) {
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();

            DecodedJWT verify = jwtVerifier.verify(jwt);

            String userInfo = verify.getClaim("userInfo").asString();

            return objectMapper.readValue(userInfo, SecurityUser.class);
        } catch (Exception e) {
            log.error("获取失败！");
            return null;
        }
    }

}
